package com.imooc.miaosha.service;

import com.imooc.miaosha.dao.UserDao;
import com.imooc.miaosha.entity.User;
import com.imooc.miaosha.result.CodeMsg;
import com.imooc.miaosha.result.Result;
import com.imooc.miaosha.util.EncodeUtils;
import com.imooc.miaosha.util.ValidatorUtil;
import com.imooc.miaosha.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author simple
 * @version 1.0
 * @date 2018/6/14 00:32
 */
@Slf4j
@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    public User getById(long id) {
        return userDao.getById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean tx() {
        User u1 = new User();
        u1.setId(3L);
        u1.setName("TheSixOneNine");
        int rowCount1 = userDao.insert(u1);
        log.error("rowCount1[{}]", rowCount1);

        User u2 = new User();
        u2.setId(2L);
        u2.setName("Test");
        int rowCount2 = userDao.insert(u1);
        log.error("rowCount2[{}]", rowCount2);

        return true;
    }

    public Result log(LoginVo loginVo) {
        if (null == loginVo) {
            return Result.error(CodeMsg.LOGIN_VO_NULL);
        }
        log.info(loginVo.toString());
        if (StringUtils.isBlank(loginVo.getMobile())) {
            return Result.error(CodeMsg.MOBILE_NULL);
        }
        if (StringUtils.isBlank(loginVo.getPassword())) {
            return Result.error(CodeMsg.PASSWORD_NULL);
        }
        if (ValidatorUtil.isNotMobile(loginVo.getMobile())) {
            return Result.error(CodeMsg.MOBILE_FORMAT_ERROR);
        }
        String mobile = loginVo.getMobile();

        User user = userDao.getByMobile(mobile);
        if (null == user) {
            return Result.error(CodeMsg.USER_NOT_EXIST);
        }
        String dbPass = user.getPassword();
        String dbSalt = user.getSalt();
        String userPass = EncodeUtils.passMd5(loginVo.getPassword(), dbSalt);
        if (!StringUtils.equals(dbPass, userPass)) {
            return Result.error(CodeMsg.PASSWORD_ERROR);
        }
        return Result.success(true);
    }
}
